package model
{
	import flash.utils.Dictionary;
	
	import WInterface.IModel;
	
	import sys.EventBase;

	/**
	 *数据模型基类 
	 * @author 张进辉
	 * 
	 */	
	public class ModelBase extends EventBase implements IModel
	{
		/**绑定回调*/
		private var _bindData:Dictionary;
		
		public function ModelBase()
		{
			super();
		}
		
		
		override public function initialize():void
		{
			super.initialize();
			
			_bindData = new Dictionary();
			addEvent(ModelEventType.MODEL_UPDATE);
		}
		
		override public function eventCallback(type:String, data:Object=null):void
		{
			var mn:ModelNotice = data as ModelNotice;
			
			if(type == ModelEventType.MODEL_UPDATE && mn && mn.className == className && mn.id == id)
			{
				var md:Object = mn.data;
				for(var key:String in md)
					setData(key,md[key]);
			}
		}
		
		public function getData(key:String):Object
		{
			if(!key) throw new Error("查找属性的key不能为空");
			var value:Object;
			
			var index:int = key.indexOf(".");
			if(index == -1)//不存在二级属性
			{
				if(hasOwnProperty(key))
					value = this[key];
			}
			else
			{
				var nextMode:IModel = getData(key.substring(0,index)) as IModel;
				if(!nextMode) throw new Error("绑定的二级对象未实现IModel");
				value = nextMode.getData(key.substr(index+1));
			}
			return value;
		}
		
		public function bind(uid:String,key:String,callback:Function):void
		{
			if(!key || !callback) throw new Error("绑定的key或回调为空");
			
			var index:int = key.indexOf(".");
			if(index == -1)//不存在二级属性
				_bindData[key] = callback;
			else//存在二级属性
			{
				var nextMode:IModel = getData(key.substring(0,index)) as IModel;
				if(!nextMode) throw new Error("绑定的二级对象未实现IModel");
				
				nextMode.bind(uid,key.substr(index+1),callback);
			}
		}
		
		/**赋值方法,由内部调用*/
		protected function setData(key:String, value:Object):void
		{
			if(hasOwnProperty(key) && this[key] != value)
			{
				this[key] = value;
				if(_bindData[key])
					_bindData[key](value);
			}
		}
		
		
		public function disconnect(uid:String):void
		{
			for(var key:String in _bindData)
				_bindData[key] = null;
			
			//清理下级属性
			
		}
		
		public function hasBindClass(uid:String):Boolean
		{
			return false;
		}
		
		
	}
}